package com.fjnu.dao.impl;

import com.fjnu.dao.CommentDao;
import com.fjnu.domain.entity.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class CommentDaoImpl implements CommentDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int insert(Comment newComment) {
        if (newComment == null || newComment.getArticleId() == null ||
                newComment.getContent() == null || newComment.getContent().trim().isEmpty()) {
            return 0;
        }

        String sql = "INSERT INTO tb_comment(content, article_id, user_id, support, oppose, create_time, update_time) " +
                "VALUES(?, ?, ?, ?, ?, NOW(), NOW())";
        return jdbcTemplate.update(sql,
                newComment.getContent(),
                newComment.getArticleId(),
                newComment.getUserId(),
                newComment.getSupport(),
                newComment.getOppose()
        );
    }

    @Override
    public int updateSupport(Integer commentId, Integer incremented) {
        if (commentId == null || incremented == null) {
            return 0;
        }
        String sql = "UPDATE tb_comment SET support = support + ?, update_time = NOW() WHERE id = ?";
        return jdbcTemplate.update(sql, incremented, commentId);
    }

    @Override
    public int updateOppose(Integer commentId, Integer incremented) {
        if (commentId == null || incremented == null) {
            return 0;
        }
        String sql = "UPDATE tb_comment SET oppose = oppose + ?, update_time = NOW() WHERE id = ?";
        return jdbcTemplate.update(sql, incremented, commentId);
    }

    @Override
    public List<Comment> selectAllCommentsForArticle(Integer articleId) {
        if (articleId == null) {
            return null;
        }
        String sql = "SELECT * FROM tb_comment WHERE article_id = ? ORDER BY create_time DESC";
        List<Comment> comments = jdbcTemplate.query(sql,
                new BeanPropertyRowMapper<>(Comment.class), articleId);
        return comments.isEmpty() ? null : comments;
    }

    @Override
    public List<Comment> selectCommentsWithLimitForArticle(Integer articleId, Integer startIndex, Integer endIndex) {
        if (articleId == null || startIndex == null || endIndex == null || startIndex < 0 || endIndex <= startIndex) {
            return null;
        }
        String sql = "SELECT * FROM tb_comment WHERE article_id = ? ORDER BY create_time DESC LIMIT ?, ?";
        List<Comment> comments = jdbcTemplate.query(sql,
                new BeanPropertyRowMapper<>(Comment.class), articleId, startIndex, endIndex - startIndex);
        return comments.isEmpty() ? null : comments;
    }
}